//
//  AttributeLabel.m
//  MyTextView
//
//  Created by Tom on 15/10/21.
//  Copyright © 2015年 Tom. All rights reserved.
//

#import "AttributeLabel.h"


#define KSepcialTextBackGoundViewtag 500

@interface AttributeLabel ()

@property(nonatomic,weak) UITextView *textView;
@property (nonatomic,strong) NSMutableArray *sepcialTextS;// 文本中所有的url／电话
@property (nonatomic,strong) RegexSepcialText *touchSepcialText;// 当前点击的url/电话

@end

@implementation AttributeLabel

#pragma mark -初始化方法

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        UITextView *textView = [[UITextView alloc] init];
        textView.editable = NO;
        textView.scrollEnabled = NO;
        textView.userInteractionEnabled = NO;
        textView.backgroundColor = [UIColor clearColor];
        textView.textContainerInset = UIEdgeInsetsMake(0, -5, 0, -5);
        [self addSubview:textView];
        self.textView = textView;
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.textView.frame = self.bounds;
}

- (NSMutableArray *)sepcialTextS{
    if (!_sepcialTextS) {
        _sepcialTextS = [NSMutableArray array];
        [_attributedStr enumerateAttributesInRange:NSMakeRange(0, _attributedStr.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
            NSString *link = attrs[Link];
            NSString *mobile = attrs[Mobile];
            if ((link==nil)&&(mobile==nil)) return ;
            RegexSepcialText *regexSepcialText = [[RegexSepcialText alloc] init];
            if (link) {
                regexSepcialText.textType = TextTypeLink;
                regexSepcialText.text = link;
            } else if (mobile) {
                regexSepcialText.textType = TextTypeMobile;
                regexSepcialText.text = mobile;
            }
            self.textView.selectedRange = range;
            NSMutableArray *rects = [NSMutableArray array];
            NSArray *selectionRects = [self.textView selectionRectsForRange:self.textView.selectedTextRange];
            for (UITextSelectionRect *selectionRect in selectionRects) {
                if (selectionRect.rect.size.width == 0 || selectionRect.rect.size.height == 0) continue;
                [rects addObject:selectionRect];
            }
            regexSepcialText.rects = rects;
            [_sepcialTextS addObject:regexSepcialText];
        }];
    }
    return _sepcialTextS;
}
- (void)setAttributedStr:(NSAttributedString *)attributedStr{
    _attributedStr = [attributedStr copy];
    self.textView.attributedText = _attributedStr;
    self.sepcialTextS = nil;
}
#pragma mark -私有方法
/**
 *  添加背景图片
 *  @param touch 触摸的特殊文本
 */
- (void)showTouchSepcialTextBackGroudView:(RegexSepcialText*)touch{
    for (UITextSelectionRect *selectionRect in touch.rects) {
        UIView *bg = [[UIView alloc] init];
        bg.tag = KSepcialTextBackGoundViewtag;
        bg.layer.cornerRadius = 3;
        bg.frame = selectionRect.rect;
        bg.backgroundColor = [UIColor lightGrayColor];
        [self insertSubview:bg atIndex:0];
    }
}
/**
 *  移除所有添加的背景view
 */
- (void)removeAllSepcialTextBackground{
    for (UIView *child in self.subviews) {
        if (child.tag == KSepcialTextBackGoundViewtag) {
            [child removeFromSuperview];
        }
    }
}
/**
 *  根据触摸点搜索触摸的特殊文本
 */
- (RegexSepcialText*)touchSepcialTextWithPoint:(CGPoint)point{
    RegexSepcialText *touchSepcialText = nil;
    for (RegexSepcialText *sepcialText in self.sepcialTextS) {
        for (UITextSelectionRect *selectionRect in sepcialText.rects) {
            if (CGRectContainsPoint(selectionRect.rect, point)) {
                touchSepcialText = sepcialText;
                break;
            }
        }
    }
    return touchSepcialText;
}

#pragma mark -监听touch事件

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)even{
    self.touchSepcialText = nil;
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:touch.view];
    self.touchSepcialText = [self touchSepcialTextWithPoint:point];
    if (self.touchSepcialText) {
       [self showTouchSepcialTextBackGroudView:self.touchSepcialText];
    }
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)even{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.touchSepcialText = nil;
        [self removeAllSepcialTextBackground];
    });
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)even{
    
    if ([self.delegate respondsToSelector:@selector(attributeLabelClick:)]) {
        if (self.touchSepcialText&&self.delegate.show) {
            [self.delegate attributeLabelClick:self.touchSepcialText];
        }
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeAllSepcialTextBackground];
    });
    
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.touchSepcialText = nil;
        [self removeAllSepcialTextBackground];
    });
}
@end
